import { deepClone } from '@/utils/util'
import WangEditor from '@/modules/FormCenter/componentsWp/WangEditor/index.vue'
import FormUpload from '@/modules/FormCenter/components/FormUpload/index.vue'
import writeInfo from '@/modules/FormCenter/componentsWp/writeInfo'
import DetailTable from '@/modules/FormCenter/componentsWp/detailTable'
import AssociationForm from '@/modules/FormCenter/componentsWp/associationForm'
import formDivider from '@/modules/FormCenter/componentsWp/divider'
import addressSelector from '@/modules/FormCenter/componentsWp/address/index.vue'
import Ocr from '@/modules/FormCenter/componentsWp/ocr/ocr.vue'
import FksAmount from '@/modules/FormCenter/componentsWp/Amount/index'
const componentChild = {}
/**
 * 将./slots中的文件挂载到对象componentChild上
 * 文件名为key，对应JSON配置中的__config__.tag
 * 文件内容为value，解析JSON配置中的__slot__
 */
const slotsFiles = require.context('./slots', false, /\.js$/)
const keys = slotsFiles.keys() || []
keys.forEach((key) => {
  const tag = key.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = slotsFiles(key).default
  componentChild[tag] = value
})

// 需要传入到组件的prop在这里定义并传入, 且在这里接收组件中的自定义事件再传入parser组件去同步更新组件中的value
function vModel(dataObject, config) {
  // 选人选部门两个组件的prop绑定的不是value
  if (config.tag === 'detail-table' && config.label) {
    dataObject.props.tableName = config.label
  }
  if (
    config.tag === 'fks-org-selector' &&
    config.defaultValue &&
    config.defaultValue.deptId
  ) {
    dataObject.props.deptId = config.defaultValue.deptId
    dataObject.props.deptName = config.defaultValue.deptName
  } else if (
    config.tag === 'fks-user-selector' &&
    config.defaultValue &&
    config.defaultValue.username
  ) {
    dataObject.props.username = config.defaultValue.username
    dataObject.props.userfullname = config.defaultValue.userfullname
  } else if (config.tag === 'write-info' && config.defaultValue) {
    dataObject.props.form = config.defaultValue
  } else if (config.tag === 'detail-table' && config.defaultValue) {
    dataObject.props.formDetail = config.defaultValue
    dataObject.props.detailPermission = this.detailPermission
  } else if (config.tag === 'association-form') {
    dataObject.props.formList = config.defaultValue ? config.defaultValue : []
    dataObject.props.permission = this.permission
  } else if (config.tagAttribute === 'wang-editor') {
    dataObject.props.permission = this.permission
    dataObject.props.value = config.defaultValue
  } else if (config.tagAttribute === 'address-selector') {
    dataObject.props.addressArr = config.defaultValue
    dataObject.props.addressTips = config.addressTips
    dataObject.props.detailAddress = config.detailAddress
  } else {
    dataObject.props.value = config.defaultValue
  }

  // 父组件为当前组件注册的事件监听器的对象，也叫listeners
  dataObject.on.input = (val) => {
    if (config.tagAttribute === 'count') {
      // 数字组件输入字母bug
      let countTest = /^[0-9.]*$/
      if (!countTest.test(val)) {
        val = val.substring(0, val.length - 1)
      }
      val = val.slice(0, 125)
    } else if (
      config.tagAttribute === 'rate' ||
      config.tagAttribute === 'slider'
    ) {
      // 评分和滑块组件会默认值为0时，更改为undefined
      val = val === 0 ? undefined : val
    }
    this.$emit('input', val)
  }
  dataObject.on.click = (val) => {
    if (config.tagAttribute == 'associate-data') {
      this.$emit('handleClickAssociate', this.conf.__vModel__)
    }
  }
  dataObject.on.change = (val) => {
    this.$emit('change', val)
  }
  // 上传组件传来的值，更新files
  dataObject.on.fileChange = (file, fileList, countFile) => {
    this.$emit('fileChange', countFile)
  }
  // 明细表更新列
  dataObject.on.detailTableChange = (val) => {
    this.$emit('detailTableChange', val)
  }
  // 关联表单
  dataObject.on.associationFormChange = (val) => {
    this.$emit('associationFormChange', val)
  }
  // 地址组件
  dataObject.on.addressChange = (val) => {
    this.$emit('addressChange', val)
  }
}

function mountSlotFiles(h, confClone, children) {
  const childObjs = componentChild[confClone.__config__.tag]
  if (childObjs) {
    Object.keys(childObjs).forEach((key) => {
      const childFunc = childObjs[key]
      if (confClone.__slot__ && confClone.__slot__[key]) {
        children.push(childFunc(h, confClone, key))
      }
    })
  }
}

function emitEvents(confClone) {
  ;['on', 'nativeOn'].forEach((attr) => {
    const eventKeyList = Object.keys(confClone[attr] || {})
    eventKeyList.forEach((key) => {
      const val = confClone[attr][key]
      if (typeof val === 'string') {
        confClone[attr][key] = (event) => this.$emit(val, event)
      }
    })
  })
}

function buildDataObject(confClone, dataObject) {
  Object.keys(confClone).forEach((key) => {
    const val = confClone[key]
    if (key === '__vModel__') {
      vModel.call(this, dataObject, confClone.__config__)
    } else if (key === 'disabled') {
      dataObject.attrs['disabled'] = val
    } else if (key === 'totalDisabled') {
      dataObject.attrs['disabled'] = val
    } else if (key === 'required') {
      dataObject.attrs['required'] = val
    } else if (key === 'totalRequired') {
      dataObject.attrs['required'] = val
    } else if (dataObject[key] !== undefined) {
      if (
        dataObject[key] === null ||
        dataObject[key] instanceof RegExp ||
        ['boolean', 'string', 'number', 'function'].includes(
          typeof dataObject[key]
        )
      ) {
        dataObject[key] = val
      } else if (Array.isArray(dataObject[key])) {
        dataObject[key] = [...dataObject[key], ...val]
      } else {
        dataObject[key] = { ...dataObject[key], ...val }
      }
    } else {
      dataObject.attrs[key] = val
    }
    if (key === '__config__') {
      dataObject.ref =
        val.tagAttribute && val.tagAttribute === 'detail-table'
          ? 'detailTable'
          : ''
    }
  })

  // 清理属性
  clearAttrs(dataObject)
}

function clearAttrs(dataObject) {
  delete dataObject.attrs.__config__
  delete dataObject.attrs.__slot__
  delete dataObject.attrs.__methods__
}

function makeDataObject() {
  // 深入数据对象：
  // https://cn.vuejs.org/v2/guide/render-function.html#%E6%B7%B1%E5%85%A5%E6%95%B0%E6%8D%AE%E5%AF%B9%E8%B1%A1
  return {
    class: {},
    attrs: {},
    props: {},
    domProps: {},
    nativeOn: {},
    on: {},
    style: {},
    directives: [],
    scopedSlots: {},
    slot: null,
    key: null,
    ref: null,
    refInFor: true
  }
}

function formatInput(confClone, dataObject) {
  let str = confClone.__config__.defaultValue
  if (confClone.__config__.tag === 'fks-input' && confClone.type === 'text') {
    if (str && typeof str === 'string') {
      str = str.replace(/[^\d.]/g, '')
      str = str.split(',')
      str = str.join('')
    }
    confClone.__config__.defaultValue = str
  }
}

export default {
  props: {
    conf: {
      type: Object,
      required: true
    },
    detailPermission: {
      type: Object,
      default() {
        return {}
      }
    },
    permission: {
      type: String,
      default: ''
    }
  },
  components: {
    FormUpload,
    writeInfo,
    DetailTable,
    AssociationForm,
    formDivider,
    addressSelector,
    Ocr,
    WangEditor,
    FksAmount
  },
  render(h) {
    const dataObject = makeDataObject()
    const confClone = deepClone(this.conf)
    // console.log('render', confClone)

    const children = this.$slots.default || []
    formatInput(confClone, dataObject)

    // 如果slots文件夹存在与当前tag同名的文件，则执行文件中的代码
    mountSlotFiles.call(this, h, confClone, children)

    // 将字符串类型的事件，发送为消息
    emitEvents.call(this, confClone)

    // 将json表单配置转化为vue render可以识别的 “数据对象（dataObject）”
    buildDataObject.call(this, confClone, dataObject)
    return h(this.conf.__config__.tag, dataObject, children)
  }
}
